package com.smartyu.service;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.json.JsonGeneratorImpl;
import com.smartyu.config.ElasticSearchClientConfig;
import com.smartyu.pojo.Content;
import com.smartyu.util.HtmlParseUtil;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author ：qianyu
 * @date ：Created in 2020/5/29 23:05
 * @modified By：
 */
@Service
public class ContentService {

    @Autowired
    private HtmlParseUtil htmlParseUtil;


    @Autowired
    private RestHighLevelClient restHighLevelClient;

    //不能直接使用 @Autowired需要spring容器
    public static void main(String[] args) throws IOException {
      new ContentService().parseContent("java");
    }

    //创建索引
    public void createIndex(String index) throws IOException {
        CreateIndexRequest request=new CreateIndexRequest(index);

        //执行请求 请求后获得响应
        CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);

        System.out.println(createIndexResponse);

    }


    //1、解析数据放入es索引中
    public boolean parseContent(String keyWords) throws IOException {
        List<Content> contentList=htmlParseUtil.parseJD(keyWords);

        //把查询到的数据放入es中
        BulkRequest bulkRequest=new BulkRequest();
        bulkRequest.timeout("2m");
        for (Content content : contentList) {
            //System.out.println(content);
            bulkRequest.add(
                    new IndexRequest("jd_goods")
            .source(JSON.toJSONString(content), XContentType.JSON)
            );
        }

        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);

        return !bulk.hasFailures();
    }

    //搜索功能
    public List<Map<String,Object>> searchPage(String keyWord,int pageNo,int pageSize) throws IOException {
        if(pageNo<=1){
            pageNo=1;
        }
        //条件搜索
        SearchRequest searchRequest=new SearchRequest("jd_goods");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        //分页
        sourceBuilder.from(pageNo);
        sourceBuilder.size(pageSize);

        //精准匹配
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", keyWord);
         sourceBuilder.query(termQueryBuilder);
         sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

         //执行搜索
        searchRequest.source(sourceBuilder);
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        //解析结果
        List<Map<String,Object>>  list= new ArrayList<>();
        for (SearchHit documentFields:searchResponse.getHits().getHits()){
            list.add(documentFields.getSourceAsMap());
        }

        return list;
    }

    //高亮搜索
    public List<Map<String,Object>> searchHighlightPage(String keyWord,int pageNo,int pageSize) throws IOException {
        if(pageNo<=1){
            pageNo=1;
        }
        //条件搜索
        SearchRequest searchRequest=new SearchRequest("jd_goods");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        //分页
        sourceBuilder.from(pageNo);
        sourceBuilder.size(pageSize);

        //精准匹配
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", keyWord);
        sourceBuilder.query(termQueryBuilder);
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        //高亮搜索
        HighlightBuilder highlightBuilder=new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.requireFieldMatch(false);//多个高亮显示
        highlightBuilder.preTags("<span style='color:red;'>");
        highlightBuilder.postTags("</span>");
        sourceBuilder.highlighter(highlightBuilder);

        //执行搜素
        searchRequest.source(sourceBuilder);
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        //解析结果
        List<Map<String,Object>>  list= new ArrayList<>();
        for (SearchHit hit:searchResponse.getHits().getHits()){
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField title = highlightFields.get("title");
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();//原来的结果

             //解析高亮的字段 将原来的字段换为高亮
            if(title!=null){
                Text[] fragments = title.fragments();
                String new_title="";
                for (Text text : fragments) {
                    new_title+=text;
                    sourceAsMap.put("title",new_title);
                }
                list.add(sourceAsMap);
            }


        }

        return list;
    }

}
